<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" >
<head>
    <meta charset="UTF-8">
    <title>商品列表</title>
    <link th:href="@{/css/goodsList.css}" rel="stylesheet" type="text/css" />
    <link th:href="@{/css/orderList.css}" rel="stylesheet" type="text/css" />
    <!--    //通用方法-->
    <script th:src="@{/js/common.js}" type="text/javascript"></script>
    <!--    //jquery-->
    <script th:src="@{/js/jquery-3.6.0.min.js}" type="text/javascript"></script>
    <!--    //layer-->
    <script th:src="@{/js/layer/layer.js}" type="text/javascript"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.5.15/vue.min.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<!--最开始的设计是前端使用thymeleaf，然后发现thymeleaf性能方面不是很好，
理想的优化方式是可以使用页面静态化，但显然不符合本项目应用场景，之前的也没时间重改了，
就把秒杀和订单的业务使用vue进行操作的，中间也还有许多需要后面再优化的地方
-->
<body>
<div id="main" class="main">
<!--        商品列表-->
    <div class="titleBar">爆款秒杀</div>
    <div class="snapped_time_bar">欢迎来到AB的秒杀系统，秒杀时间和库存有限，先到先得。</div>
    <div class="snapped_main">
        <div class="goods_list" th:each="goodsVo:${goodsVoList}">
            <div class="goods_name" th:text="${goodsVo.getGoodsName()}"></div>
            <div class="goods_detail" th:text="${goodsVo.getGoodsDetail()}"></div>
            <div class="goods_stock" th:text="'库存剩余：'+${goodsVo.getStockCount()}"></div>
            <div class="time_limit" th:text="'开始时间：'+${#dates.format(goodsVo.getStartDate(), 'MMMdd HH:mm')}"></div>
            <div class="time_limit" th:text="'结束时间：'+${#dates.format(goodsVo.getEndDate(), 'MMMdd HH:mm')}"></div>
            <div class="goods_price" th:text="'秒杀价：'+${goodsVo.getDiscountPrice()}"></div>
            <div class="buy_but" th:text="立即购买" th:onclick="toDetail([[${goodsVo.getId()}]])"></div>
        </div>
    </div>
<!--        订单列表-->
    <img class="order_img" v-on:click="getOrderList" src="https://snapped-1305565335.file.myqcloud.com/goodsImg/order2.png">
    <div id="orderList" style="display: none">
        <div class="orderList" v-for="(order,i) in orderList" v-on:click="toOrderDetail(order)">
            <div class="order_top_bar">
                订单号：{{order.userId}}{{order.goodsId}}{{order.id}} | 成都信息工程大学 | {{order.createDate|formatDate(2)}}  | 在线支付
            </div>
            <div class="order_list_main">
                <img class="order_list_img" v-bind:src="order.goodsImg">
                <div style="float: left">
                    <div class="order_list_goods_name">{{order.goodsName}} * 1</div>
                    <div class="order_price">订单价格：{{order.goodsPrice}}</div>
                </div>
                <div class="order_statue">{{orderStatus[order.status]}}</div>
            </div>
        </div>
    </div>
<!--        商品详情弹窗-->
    <div id="detail_main" style="display: none">
        <div class="detail" >
            <div class="left_detail_bar" style="float: left">
                <img class="goods_img" v-bind:src="goodsVoDetail.goodsImg">
                <div class="remain_second" style="color: orangered" >倒计时：{{nowTime|diffTime(goodsVoDetail.startDate)}}</div>
            </div>
            <div class="right_detail_bar" style="float: right">
                <div class="goods_name" style="color: black">{{goodsVoDetail.goodsName}}</div>
                <div class="goods_detail" style="color: #8a8a8a">{{goodsVoDetail.goodsDetail}}</div>
                <div class="goods_stock" style="color: black" >库存剩余：{{goodsVoDetail.goodsStock}}</div>
                <div class="time_limit"  style="color: black" >开始时间：{{goodsVoDetail.startDate|formatDate(1)}}</div>
                <div class="time_limit" style="color: black" >结束时间：{{goodsVoDetail.endDate|formatDate(1)}}</div>
                <div class="goods_price" style="color: orangered" >秒杀价：{{goodsVoDetail.discountPrice}}</div>
                <div class="buy_but" style="margin-top: 20px" v-if="nowTime.getTime()>=new Date(goodsVoDetail.startDate).getTime()" @click="snap(goodsVoDetail.id)">立即购买</div>
                <div class="buy_but" style="margin-top: 20px;background-color: #8a8a8a" v-if="nowTime.getTime()< new Date(goodsVoDetail.startDate).getTime()" >未开始</div>
            </div>
        </div>
    </div>
<!--    订单详情弹窗-->
    <div id="order_detail" style="display: none">
        <div class="detail" >
            <div class="left_detail_bar" style="float: left">
                <img class="goods_img" v-bind:src="orderDetail.goodsImg">
            </div>
            <div class="right_detail_bar" style="float: right">
                <div class="goods_name" style="color: #fc7930">恭喜您抢到了！！</div>
                <div class="goods_detail" style="color: #8a8a8a">商品名称：{{orderDetail.goodsName}}</div>
                <div class="goods_detail" style="color: #8a8a8a" >订单价格：{{orderDetail.goodsPrice}}</div>
                <div class="goods_detail" style="color: #8a8a8a" >下单时间：{{orderDetail.createDate|formatDate(2)}}</div>
                <div class="goods_detail" style="color: #8a8a8a" >订单状态：{{orderStatus[orderDetail.status]}}</div>
                <div class="goods_detail" style="color: #8a8a8a" >联系方式：张三 15082665243</div>
                <div class="goods_detail" style="color: #8a8a8a" >收货地址：成都信息工程大学</div>
                <div class="buy_but" style="margin-top: 20px" v-if="orderDetail.status === 0" @click="payOrder(orderDetail.id,orderDetail.status)">立即支付</div>
                <div class="buy_but" style="margin-top: 20px;background-color: #8a8a8a" v-if="orderDetail.status !== 0" >{{orderStatus[orderDetail.status]}}</div>
            </div>
        </div>
    </div>
</div>
</body>
<script>
    //在月份、日期、小时等小于10前面补0
    const padDate = function (value) {
        // return value < 10 ? '0' + value : value;
        return value;
    };
    let thisV = new Vue({
        el:"#main",
        data:{
            goodsVoDetail:{
                discountPrice: 16.9,
                endDate: "2021-07-24T14:53:02.000+00:00",
                goodsDetail: "MySQL 是全球最受欢迎的开源数据库之一，广泛应用于各类互联网应用场景",
                goodsImg: "https://snapped-1305565335.file.myqcloud.com/goodsImg/mysql.png",
                goodsName: "云数据库MySQL",
                goodsPrice: 19.9,
                goodsStock: 100,
                goodsTitle: "MySQL",
                id: 1,
                startDate: "2021-07-15T14:52:57.000+00:00",
                stockCount: 20
            },
            goodsVoList:[],
            orderDetail:{
                createDate: "2021-07-18T06:02:02.483+00:00",
                deliveryAddrId: 0,
                goodsCount: 1,
                goodsId: 2,
                goodsName: "PolarDB MySQL版",
                goodsPrice: 28.99,
                id: 11,
                orderChannel: 1,
                payDate: null,
                status: 0,
                userId: 1,
            },
            orderList:[],
            remainTime:0,
            nowTime:new Date(),
            errMsg:"服务器出错",
            timeLimit:true,
            orderStatus:["未支付","待发货","待签收","已收货","已退款","已完成"],
        },
        // 配置过滤器进行时间格式修改和倒计时处理
        filters: {
            formatDate:function (value,type) {
                let date = new Date(value);
                let year = date.getFullYear();
                let month = padDate(date.getMonth()+1);
                let day = padDate(date.getDate());
                let hours = padDate(date.getHours());
                let minutes = padDate(date.getMinutes());
                let seconds = padDate(date.getSeconds());
                if (type===1){
                    return  month + '月' + day  + ' ' + hours + ':' + minutes;
                }else {
                    return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
                }

            },
            diffTime:function (now,detailTime) {
                if (!now) {
                    return '已开抢'
                }
                let goodsTime = new Date(detailTime).getTime();
                let timeNow = new Date(now).getTime();
                let minute = 1000 * 60;
                let hour = minute * 60;
                let day = hour * 24;
                let halfamonth = day * 15;
                let month = day * 30;

                let diffValue =goodsTime - timeNow;
                let monthC =diffValue/month;
                let weekC =diffValue/(7*day);
                let dayC =diffValue/day;
                let hourC =diffValue/hour;
                let minC =diffValue/minute;
                if (diffValue<0){
                    this.remainTime = "已开抢";
                    this.timeLimit = true;
                }else if (parseInt(monthC) >=1) {
                    this.remainTime = parseInt(monthC) + '个月' + parseInt(dayC)%30 + '天';
                } else if (parseInt(dayC) >=1) {
                    this.remainTime = parseInt(dayC) + '天' +parseInt(hourC)%24 +"小时";
                }else if(parseInt(hourC)>=1){
                    this.remainTime = parseInt(hourC) +"小时" + parseInt(minC)%60 +"分";
                } else if(parseInt(minC)>=1){
                    this.remainTime = parseInt(minC) +"分" + parseInt(diffValue/1000)%60+"秒";
                } else if(parseInt(diffValue)>=1){
                    this.remainTime = parseInt(diffValue/1000)+"秒";
                }else {
                    this.remainTime = "已开抢";
                    this.timeLimit = true;
                }
                return this.remainTime;
            }
        },
        methods:{
            //秒杀请求
            snap:function(id){
                layer.closeAll();
                axios.get('/snap/do_snap/', {
                    params: {
                        goodsId: id
                    }
                })
                    .then(function (response) {
                        console.log(response);
                        if (response.data.code === 0){
                            //轮询秒杀结果，延时开始削峰
                            layer.msg('排队中，请稍等...', {icon: 1});
                            setTimeout(function (){
                                thisV.waitSnapResult(id);
                            },1000);

                        }else {
                            thisV.$data.errMsg = response.data.msg;
                            layer.alert(thisV.$data.errMsg, {icon: 5});
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            //轮询获取秒杀结果
            waitSnapResult:function (id){
                layer.closeAll();
                layer.msg('排队中，请稍等...', {icon: 1});
                axios.get('/snap/result/', {
                    params: {
                        goodsId: id
                    }
                })
                    .then(function (response) {
                        console.log(response);
                        if (response.data.code === 0){
                            //跳转订单详情
                            thisV.toOrderDetail(response.data.data)
                        }else {
                           let codeMsg = response.data;
                           if (codeMsg.code === 500513){
                               //排队中，继续轮询
                               setTimeout(function (){
                                   thisV.waitSnapResult(id);
                               },1000);
                           }else {
                               layer.alert(codeMsg.msg, {icon: 5});
                           }

                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            //跳转订单详情
            toOrderDetail:function (order){
                thisV.orderDetail = order;
                layer.closeAll();
                layer.open({
                    type:1,
                    title: '订单详情',
                    skin:'layer_skin',
                    content: $("#order_detail"),
                    area: ['800px', '500px'],
                })
            },
            //支付
            payOrder:function (orderId,status){
                if (status !== 0){
                    return;
                }
                layer.closeAll();
                axios.get('/pay_order/'+orderId)
                    .then(function (response) {
                        console.log(response);
                        if (response.data.code === 0){
                            layer.msg('支付成功！', {icon: 1});
                            thisV.getOrderList();
                        }else {
                            layer.msg("支付失败", {icon: 5});
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

            },
            //获取订单列表
            getOrderList:function (){
                axios.get('/to_order_list')
                    .then(function (response) {
                        console.log(response);
                        if (response.data.code === 0){
                            thisV.$data.orderList = response.data.data;
                            layer.open({
                                type: 1,
                                area: ['600px', '800px'],
                                title: '订单列表',
                                content:  $("#orderList"),
                                offset: 'r',
                            });
                        }else {
                            thisV.$data.errMsg = response.data.msg;
                            layer.alert(thisV.$data.errMsg, {icon: 5});
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

            },
        },
        mounted:function (){
            let _this = this;
            this.timer = setInterval(function(){
                _this.nowTime = new Date(); //修改数据date
            },1000);
        },
        //实例销毁之前调用
        beforeDestroy:function(){
            if(this.timer){
                clearInterval(this.timer); //在Vue实例销毁前，清除定时器
            }
        },

    })
    // 跳转商品详情
    function toDetail(goodsId){  //获取商品详情，预处理时间
        axios.get('/goods/to_detail/'+goodsId)
            .then(function (response) {
                console.log(response);
                thisV.$data.goodsVoDetail = response.data.data;
                layer.open({
                    type:1,
                    title: '详情',
                    skin:'layer_skin',
                    content: $("#detail_main"),
                    area: ['800px', '500px'],
                })
            })
            .catch(function (error) {
                console.log(error);
            });
    }
</script>
</html>